package com.easyadmin.service.impl;

import com.easyadmin.entity.enums.PageSize;
import com.easyadmin.entity.enums.ResponseCodeEnum;
import com.easyadmin.entity.po.SysAccount;
import com.easyadmin.entity.po.SysRole;
import com.easyadmin.entity.po.SysRole2Menu;
import com.easyadmin.entity.query.SysAccountQuery;
import com.easyadmin.entity.query.SysRole2MenuQuery;
import com.easyadmin.entity.query.SysRoleQuery;
import com.easyadmin.entity.vo.PaginationResult;
import com.easyadmin.entity.vo.SimplePage;
import com.easyadmin.exception.BusinessException;
import com.easyadmin.mappers.SysAccountMapper;
import com.easyadmin.mappers.SysRole2MenuMapper;
import com.easyadmin.mappers.SysRoleMapper;
import com.easyadmin.service.SysRoleService;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 *
 * 系统角色表 业务接口实现
 *
 */
@Service("sysRoleService")
public class SysRoleServiceImpl implements SysRoleService {

    @Resource
    private SysRoleMapper<SysRole, SysRoleQuery> sysRoleMapper;

    @Resource
    private SysAccountMapper<SysAccount, SysAccountQuery> sysAccountMapper;

    @Resource
    private SysRole2MenuMapper<SysRole2Menu, SysRole2MenuQuery> sysRole2MenuMapper;


    /**
     * 根据条件查询列表
     */
    @Override
    public List<SysRole> findListByParam(SysRoleQuery param) {
        return this.sysRoleMapper.selectList(param);
    }

    /**
     * 根据条件查询列表
     */
    @Override
    public Integer findCountByParam(SysRoleQuery param) {
        return this.sysRoleMapper.selectCount(param);
    }

    /**
     * 分页查询方法
     */
    @Override
    public PaginationResult<SysRole> findListByPage(SysRoleQuery param) {
        int count = this.sysRoleMapper.selectCount(param);
        int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();
        int pageNo = 0;
        if (null != param.getPageNo()) {
            pageNo = param.getPageNo();
        }
        SimplePage page = new SimplePage(pageNo, count, pageSize);
        param.setSimplePage(page);
        List<SysRole> list = this.sysRoleMapper.selectList(param);
        PaginationResult<SysRole> result = new PaginationResult<>(count, pageSize, pageNo, page.getPageTotal(), list);
        return result;
    }

    /**
     * 新增
     */
    @Override
    public Integer add(SysRole bean) throws BusinessException {
        try {
            return this.sysRoleMapper.insert(bean);
        } catch (DuplicateKeyException e) {
            throw new BusinessException("信息已经存在");
        }
    }

    /**
     * 批量新增
     */
    @Override
    public Integer addBatch(List<SysRole> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.sysRoleMapper.insertBatch(listBean);
    }

    /**
     * 批量新增或者修改
     */
    @Override
    public Integer addOrUpdateBatch(List<SysRole> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.sysRoleMapper.insertOrUpdateBatch(listBean);
    }

    /**
     * 根据RoleId修改
     */
    @Override
    public Integer updateByRoleId(SysRole bean, Integer roleId) {
        return this.sysRoleMapper.updateByRoleId(bean, roleId);
    }


    /**
     * 根据RoleId删除
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer deleteByRoleId(Integer roleId) throws BusinessException {
        SysAccountQuery query = new SysAccountQuery();
        query.setRoles(String.valueOf(roleId));
        int count = sysAccountMapper.selectCount(query);
        if (count > 0) {
            throw new BusinessException("角色正在被使用无法删除");
        }
        count = this.sysRoleMapper.deleteByRoleId(roleId);
        this.sysRole2MenuMapper.deleteByRoleId(roleId);
        return count;
    }


    /**
     * 根据RoleId获取对象
     */
    @Override
    public SysRole getSysRoleByRoleId(Integer roleId) {
        SysRole sysRole = this.sysRoleMapper.selectByRoleId(roleId);
        sysRole.setMenuIds(this.sysRole2MenuMapper.selectMenuIdsByRoleIds(new String[]{sysRole.getRoleId().toString()}));
        return sysRole;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRole(SysRole sysRole, String menuIds) throws BusinessException {
        Integer roleId = sysRole.getRoleId();
        if (null == roleId) {
            Date curDate = new Date();
            sysRole.setCreateTime(curDate);
            sysRole.setLastUpdateTime(curDate);
            this.sysRoleMapper.insert(sysRole);
            roleId = sysRole.getRoleId();
        } else {
            this.sysRoleMapper.updateByRoleId(sysRole, roleId);
        }

        SysRoleQuery roleQuery = new SysRoleQuery();
        roleQuery.setRoleName(sysRole.getRoleName());
        Integer roleCount = sysRoleMapper.selectCount(roleQuery);
        if (roleCount > 1) {
            throw new BusinessException("角色已存在");
        }
        saveRoleMenu(roleId, menuIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRoleMenu(Integer roleId, String menuIds) throws BusinessException {
        if (null == roleId || menuIds == null) {
            throw new BusinessException("请求参数错误", ResponseCodeEnum.CODE_600.getCode());
        }

        this.saveRole2Menu(roleId, menuIds);
    }

    private void saveRole2Menu(Integer roleId, String menuIds) {
        this.sysRole2MenuMapper.deleteByRoleId(roleId);
        List<SysRole2Menu> roleToMenus = new ArrayList<>();
        String[] menuIdsArray = menuIds.split(",");
        for (String menuId : menuIdsArray) {
            SysRole2Menu roleToMenu = new SysRole2Menu();
            roleToMenu.setMenuId(Integer.parseInt(menuId));
            roleToMenu.setRoleId(roleId);
            roleToMenus.add(roleToMenu);
        }
        if (!roleToMenus.isEmpty()) {
            sysRole2MenuMapper.insertBatch(roleToMenus);
        }
    }
}